import Vue from 'vue'
import Vuex from 'vuex'
import axios from '../axios/axios.js'
let near
if (localStorage.getItem('nearCity') != 'undefined') {
    console.log(localStorage.getItem('nearCity'))
    near = JSON.parse(localStorage.getItem('nearCity'))
}
Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        isLogin: sessionStorage.getItem('isLogin'),
        cityPosition: localStorage.getItem('cityPosition') || '上海',
        nearCity: near || [],
        userName: sessionStorage.getItem('userName') || '',
    },
    mutations: {
        saveUserName(state, { data }) {
            state.isLogin = !!data
            state.userName = data
            sessionStorage.setItem('userName', data)
            sessionStorage.setItem('isLogin', !!data)
        },
        changeCity(state, { location }) {
            state.cityPosition = location
            localStorage.setItem('cityPosition', location)
        },
        changeNearCity(state, { nearCity }) {
            state.nearCity = nearCity
            localStorage.setItem('nearCity', JSON.stringify(nearCity))
        },
        logout() {
             sessionStorage.removeItem('isLogin')
            sessionStorage.removeItem('userName')

            
        },
    },
    actions: {
        async loginIn({ commit }, { userName, password }) {
            try {
                const res = await axios.get('/api/meituan/login', { params: { userName, password } })
                if (res.status == 'success') {
                    commit('saveUserName', res)
                    console.log(res)
                }
                return res
            } catch (err) {
                return err
            }
        },
        async register({ commit }, { userName, password, rePassword }) {
            try {
                const res = await axios.get('/api/meituan/register', { params: { userName, password, rePassword } })
                console.log(res)
                if (res.status === 'success') {
                    commit('saveUserName', res)
                }
                return res
            } catch (err) {
                return err
            }
        },
        async getRequest(context, { path }) {
            try {
                const { status, data } = await axios.get(path)
                if (status == 'success') {
                    // console.log(data);
                    return data
                }
            } catch (err) {
                return err
            }
        },
        async getPosition({ commit }) {
            const { status, data } = await axios.get(' /api/meituan/city/getPosition.json')
            if (status == 'success') {
                commit('changeCity', { location: data.name })
                commit('changeNearCity', { nearCity: data.nearCity })
                console.log(data);
            }
        },
    },

})
